package com.nnnu.wsnackshop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nnnu.wsnackshop.exception.ObjectException;
import com.nnnu.wsnackshop.mapper.ProductSpuMapper;
import com.nnnu.wsnackshop.pojo.dto.AddSkuDTO;
import com.nnnu.wsnackshop.pojo.dto.SkuPageDTO;
import com.nnnu.wsnackshop.pojo.dto.UpdateSkuDTO;
import com.nnnu.wsnackshop.pojo.entity.ProductSku;
import com.nnnu.wsnackshop.mapper.ProductSkuMapper;
import com.nnnu.wsnackshop.pojo.entity.ProductSpu;
import com.nnnu.wsnackshop.pojo.vo.SkuVO;
import com.nnnu.wsnackshop.pojo.vo.SpuVO;
import com.nnnu.wsnackshop.result.PageResult;
import com.nnnu.wsnackshop.service.IProductSkuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品SKU表 服务实现类
 * </p>
 *
 * @author zk
 * @since 2025-05-14
 */
@Service
@RequiredArgsConstructor
public class ProductSkuServiceImpl extends ServiceImpl<ProductSkuMapper, ProductSku> implements IProductSkuService {

    private final ProductSpuMapper spuMapper;

    @Override
    public PageResult<SkuVO> pageSku(SkuPageDTO dto) {
        Page<ProductSku> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        LambdaQueryWrapper<ProductSku> qw = Wrappers.<ProductSku>lambdaQuery()
                .eq(dto.getSpuId() != null, ProductSku::getSpuId, dto.getSpuId())
                .eq(dto.getProductId() != null, ProductSku::getProductId, dto.getProductId())
                .like(StrUtil.isNotBlank(dto.getTitle()), ProductSku::getTitle, dto.getTitle())
                .eq(dto.getSaleable() != null, ProductSku::getSaleable, dto.getSaleable());
        Page<ProductSku> r = baseMapper.selectPage(page, qw);
        List<SkuVO> vos = r.getRecords().stream().map(sku -> {
            SkuVO vo = BeanUtil.copyProperties(sku, SkuVO.class);
            vo.setSpuTitle(
                    Optional.ofNullable(spuMapper.selectById(sku.getSpuId())).map(ProductSpu::getTitle).orElse(""));
            vo.setImages(JSONUtil.toList(sku.getImages(), String.class));
            vo.setStock(sku.getStock());
            return vo;
        }).toList();
        return new PageResult<>(r.getTotal(), vos);
    }

    @Override
    public void addSku(AddSkuDTO dto) {
        ProductSku sku = BeanUtil.copyProperties(dto, ProductSku.class);
        baseMapper.insert(sku);
    }

    @Override
    public void updateSku(UpdateSkuDTO dto) {
        ProductSku sku = baseMapper.selectById(dto.getId());
        if (sku == null)
            throw new ObjectException("SKU不存在");
        // 只复制非空字段，避免覆盖其他字段
        BeanUtil.copyProperties(dto, sku, true);
        baseMapper.updateById(sku);
    }

    @Override
    public SkuVO getSkuDetail(Integer id) {
        ProductSku sku = baseMapper.selectById(id);
        if (sku == null)
            throw new ObjectException("SKU不存在");
        SkuVO vo = BeanUtil.copyProperties(sku, SkuVO.class);
        vo.setSpuTitle(Optional.ofNullable(spuMapper.selectById(sku.getSpuId())).map(ProductSpu::getTitle).orElse(""));
        vo.setImages(JSONUtil.toList(sku.getImages(), String.class));
        vo.setStock(sku.getStock());
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteSku(List<Integer> ids) {
        baseMapper.deleteBatchIds(ids);
    }

    @Override
    public void exportSku(HttpServletResponse resp) throws IOException {
        setExcelHeader(resp, "SKU列表");
        try (ExcelWriter writer = EasyExcel.write(resp.getOutputStream(), SkuVO.class).build()) {
            WriteSheet sheet = EasyExcel.writerSheet("SKU").build();
            List<SkuVO> all = baseMapper.selectList(null).stream().map(spu -> BeanUtil.copyProperties(spu, SkuVO.class))
                    .toList();
            writer.write(all, sheet);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importSku(MultipartFile file) throws IOException {

        List<SkuVO> list = EasyExcel.read(file.getInputStream(), SpuVO.class, null).sheet().doReadSync();
        saveBatch(list.stream().map(vo -> BeanUtil.copyProperties(vo, ProductSku.class)).toList());
    }

    @Override
    public void downloadSkuTemplate(HttpServletResponse resp) throws IOException {

        setExcelHeader(resp, "SKU导入模板");
        EasyExcel.write(resp.getOutputStream(), SkuVO.class).sheet("模板").doWrite(Collections.emptyList());
    }

    @Override
    public List<SkuVO> listSkuBySpu(Integer spuId) {
        // 需要在实现类中实现，示例：
        LambdaQueryWrapper<ProductSku> qw = new LambdaQueryWrapper<>();
        qw.eq(ProductSku::getSpuId, spuId)
                .eq(ProductSku::getSaleable, Boolean.TRUE)
                .eq(ProductSku::getValid, Boolean.TRUE);
        List<ProductSku> entities = this.baseMapper.selectList(qw);
        // 转换为 VO
        return entities.stream().map(entity -> {
            SkuVO vo = BeanUtil.copyProperties(entity, SkuVO.class);
            if (entity.getImages() != null) {
                try {
                    vo.setImages(new ObjectMapper().readValue(entity.getImages(), new TypeReference<>() {
                    }));
                } catch (Exception e) {
                    log.warn("解析 SKU images 失败, id=" + entity.getId());
                }
            }
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public List<SkuVO> listSkuByProduct(Integer productId) {
        LambdaQueryWrapper<ProductSku> qw = new LambdaQueryWrapper<>();
        qw.eq(ProductSku::getProductId, productId)
                .eq(ProductSku::getSaleable, Boolean.TRUE)
                .eq(ProductSku::getValid, Boolean.TRUE);
        List<ProductSku> entities = this.baseMapper.selectList(qw);
        // 转换为 VO
        return entities.stream().map(entity -> {
            SkuVO vo = BeanUtil.copyProperties(entity, SkuVO.class);
            if (entity.getImages() != null) {
                try {
                    vo.setImages(new ObjectMapper().readValue(entity.getImages(), new TypeReference<>() {
                    }));
                } catch (Exception e) {
                    log.warn("解析 SKU images 失败, id=" + entity.getId());
                }
            }
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public void updateSkuStock(Integer id, Integer stock) {
        ProductSku sku = baseMapper.selectById(id);
        if (sku == null) {
            throw new ObjectException("SKU不存在");
        }
        sku.setStock(stock);
        baseMapper.updateById(sku);
    }

    private void setExcelHeader(HttpServletResponse resp, String name) {
        String fileName = URLEncoder.encode(name, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        resp.setCharacterEncoding("utf-8");
        resp.setHeader("Content-Disposition", "attachment;filename*=UTF-8''" + fileName + ".xlsx");
    }

}
